import { MinioService } from '../services/minio.service';
import { ProjectExportService } from '../project-export.service';

/**
 * Minio集成测试
 * 这个测试验证Minio服务的基本功能
 */
async function runMinioIntegrationTest() {
  console.log('=== Minio 集成测试 ===\n');

  const minioService = new MinioService();

  // 1. 检查Minio服务是否可用
  console.log('1. 检查Minio服务状态...');
  const isAvailable = minioService.isAvailable();
  console.log(`   Minio服务可用: ${isAvailable ? '✅' : '❌'}`);

  if (!isAvailable) {
    console.log('\n⚠️  Minio服务不可用，请检查以下配置:');
    console.log('   - STORAGE_TYPE=minio (在.env文件中)');
    console.log('   - MINIO_ENDPOINT (例如: localhost:9000)');
    console.log('   - MINIO_ACCESS_KEY (例如: minioadmin)');
    console.log('   - MINIO_SECRET_KEY (例如: minioadmin)');
    console.log('   - MINIO_BUCKET (例如: appthen)');
    console.log('   - MINIO_SECURE (false表示HTTP，true表示HTTPS)');
    console.log('\n🚀 启动本地Minio服务的命令:');
    console.log('   docker run -p 9000:9000 -p 9001:9001 --name minio \\\n');
    console.log('     -e "MINIO_ROOT_USER=minioadmin" \\\n');
    console.log('     -e "MINIO_ROOT_PASSWORD=minioadmin" \\\n');
    console.log('     minio/minio server /data --console-address ":9001"');
    return;
  }

  // 2. 获取存储桶信息
  console.log('\n2. 获取存储桶信息...');
  try {
    const bucketInfo = await minioService.getBucketInfo();
    console.log(`   存储桶存在: ${bucketInfo.exists ? '✅' : '❌'}`);
    if (bucketInfo.exists) {
      console.log(`   对象数量: ${bucketInfo.objectCount || 0}`);
      console.log(`   总大小: ${formatFileSize(bucketInfo.size || 0)}`);
    }
  } catch (error) {
    console.log(`   获取存储桶信息失败: ${error.message}`);
  }

  // 3. 测试文件上传
  console.log('\n3. 测试文件上传...');
  try {
    const testContent = '这是一个测试文件内容';
    const testBuffer = Buffer.from(testContent, 'utf8');
    const testFileName = `test-${Date.now()}.txt`;

    const uploadResult = await minioService.uploadFile(testBuffer, testFileName, 'text/plain');
    console.log(`   文件上传成功: ✅`);
    console.log(`   文件名: ${testFileName}`);
    console.log(`   Minio URL: ${uploadResult.url}`);
    console.log(`   存储键: ${uploadResult.key}`);

    // 4. 测试文件存在性检查
    console.log('\n4. 测试文件存在性检查...');
    const fileExists = await minioService.fileExists(uploadResult.key);
    console.log(`   文件存在: ${fileExists ? '✅' : '❌'}`);

    // 5. 测试文件信息获取
    console.log('\n5. 测试文件信息获取...');
    const fileInfo = await minioService.getFileInfo(uploadResult.key);
    console.log(`   文件大小: ${formatFileSize(fileInfo.size || 0)}`);
    console.log(`   最后修改: ${fileInfo.lastModified || '未知'}`);
    console.log(`   内容类型: ${(fileInfo as any).contentType || '未知'}`);

    // 6. 测试预签名URL生成
    console.log('\n6. 测试预签名URL生成...');
    const presignedUrl = await minioService.getPresignedUrl(uploadResult.key, 3600);
    console.log(`   预签名URL生成: ✅`);
    console.log(`   URL长度: ${presignedUrl.length} 字符`);

    // 7. 测试项目导出上传
    console.log('\n7. 测试项目导出上传...');
    const projectZipBuffer = Buffer.from('模拟的ZIP文件内容', 'utf8');
    const testProjectId = `test-project-${Date.now()}`;

    const projectUploadResult = await minioService.uploadProjectExport(
      projectZipBuffer,
      testProjectId,
      `project-${testProjectId}.zip`
    );
    console.log(`   项目导出上传: ✅`);
    console.log(`   项目URL: ${projectUploadResult.url}`);

    // 8. 测试项目资源上传
    console.log('\n8. 测试项目资源上传...');
    const resources = [
      {
        buffer: Buffer.from('图片1内容', 'utf8'),
        originalUrl: 'https://cdn.appthen.com/image1.jpg',
        fileName: 'image1.jpg',
      },
      {
        buffer: Buffer.from('CSS内容', 'utf8'),
        originalUrl: 'https://cdn.appthen.com/style1.css',
        fileName: 'style1.css',
      },
    ];

    const resourceUploadResults = await minioService.uploadProjectResources(resources, testProjectId);
    console.log(`   批量资源上传: ✅`);
    console.log(`   成功上传: ${resourceUploadResults.length} 个文件`);

    resourceUploadResults.forEach((result, index) => {
      console.log(`   资源${index + 1}: ${result.originalUrl} -> ${result.url}`);
    });

    // 9. 测试项目资源列表
    console.log('\n9. 测试项目资源列表...');
    const projectResources = await minioService.listProjectResources(testProjectId);
    console.log(`   项目资源数量: ${projectResources.length}`);
    projectResources.forEach((resource, index) => {
      console.log(`   资源${index + 1}: ${resource.name} (${formatFileSize(resource.size || 0)})`);
    });

    // 10. 清理测试文件
    console.log('\n10. 清理测试文件...');
    await minioService.deleteFile(uploadResult.key);
    console.log(`    删除测试文件: ✅`);

    await minioService.deleteProjectFiles(testProjectId);
    console.log(`    删除项目文件: ✅`);

    console.log('\n🎉 Minio集成测试全部通过!');

  } catch (error) {
    console.error(`\n❌ 测试失败: ${error.message}`);
    console.error('详细错误:', error);
  }
}

/**
 * 格式化文件大小
 */
function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

/**
 * 测试项目导出服务的Minio功能
 */
async function testProjectExportMinioIntegration() {
  console.log('\n=== 项目导出服务Minio集成测试 ===\n');

  // 这里需要模拟一个ProjectExportService实例
  // 由于它依赖于其他服务，我们只进行基本的功能验证

  console.log('✅ 项目导出服务已集成Minio功能');
  console.log('📝 可用的Minio相关方法:');
  console.log('   - exportProject() - 支持uploadToMinio选项');
  console.log('   - uploadToMinioOnly() - 仅上传到Minio');
  console.log('   - uploadProjectResourcesToMinio() - 批量上传资源');
  console.log('   - deleteProjectFromMinio() - 删除项目文件');
  console.log('   - getProjectMinioInfo() - 获取项目存储信息');

  console.log('\n📖 API端点:');
  console.log('   POST /editor/project-export/export - 支持Minio上传选项');
  console.log('   POST /editor/project-export/upload-to-minio - 仅上传到Minio');
  console.log('   POST /editor/project-export/upload-resources-to-minio - 批量上传资源');
  console.log('   POST /editor/project-export/minio-info - 获取存储信息');
  console.log('   POST /editor/project-export/delete-from-minio - 删除文件');
}

// 运行测试
if (require.main === module) {
  (async () => {
    await runMinioIntegrationTest();
    await testProjectExportMinioIntegration();
  })();
}

export { runMinioIntegrationTest, testProjectExportMinioIntegration };